/*
 *    Copyright 2009-2022 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.logging;

import org.apache.ibatis.scripting.LanguageDriverRegistry;
import org.apache.ibatis.type.IntegerTypeHandler;

import java.lang.reflect.Constructor;

/**
 * 日志工厂
 * MyBatis 提供了 trace debug warn erorr 四个级别，这基本与主流日志框架的日志级别类似，可以满足绝大多数场景的日志需求
 * (java.util.logging提供了All FINEST FINER FINE CONFIG INFO WARNING 9种级别，而 Log4j2 则只有
 * trace debug info warn error fatal 种日志级别。)
 *
 * Ext: 扩展点1
 * 1、这里的 useCustomLogging 被 Configuration.setLogImpl(Class<? extends Log> logImpl) 调用，可以用来使用我们自己定义的日志实现；
 * @author Clinton Begin
 * @author Eduardo Macarron
 */
public final class LogFactory {

  /**
   * Marker to be used by logging implementations that support markers.
   * 支持标记的日志记录实现使用的标记。
   */
  public static final String MARKER = "MYBATIS";

  /**
   * 记录当前使用的第三方日志组件所对应的适配器的构造方法
   */
  private static Constructor<? extends Log> logConstructor;

  static {
    // 下面会针对每种 日志组件调用 tryImplementation ）方法进行尝试加载，具体调用顺序是（这个顺序就是优先级，前者被加载后后者便不再使用）：
    // useSlf4jLogging -> useCommonsLogging -> useLog4J2Logging -> useLog4JLogging -> useJdkLogging -> useNoLogging
    tryImplementation(LogFactory::useSlf4jLogging);
    tryImplementation(LogFactory::useCommonsLogging);
    tryImplementation(LogFactory::useLog4J2Logging);
    tryImplementation(LogFactory::useLog4JLogging);
    tryImplementation(LogFactory::useJdkLogging);
    tryImplementation(LogFactory::useNoLogging);
  }

  private LogFactory() {
    // disable construction
  }

  public static Log getLog(Class<?> clazz) {
    return getLog(clazz.getName());
  }

  public static Log getLog(String logger) {
    try {
      return logConstructor.newInstance(logger);
    } catch (Throwable t) {
      throw new LogException("Error creating logger for logger " + logger + ".  Cause: " + t, t);
    }
  }

  public static synchronized void useCustomLogging(Class<? extends Log> clazz) {
    setImplementation(clazz);
  }

  public static synchronized void useSlf4jLogging() {
    setImplementation(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
  }

  public static synchronized void useCommonsLogging() {
    setImplementation(org.apache.ibatis.logging.commons.JakartaCommonsLoggingImpl.class);
  }

  /**
   * @deprecated Since 3.5.9 - See https://github.com/mybatis/mybatis-3/issues/1223. This method will remove future.
   */
  @Deprecated
  public static synchronized void useLog4JLogging() {
    setImplementation(org.apache.ibatis.logging.log4j.Log4jImpl.class);
  }

  public static synchronized void useLog4J2Logging() {
    setImplementation(org.apache.ibatis.logging.log4j2.Log4j2Impl.class);
  }

  public static synchronized void useJdkLogging() {
    setImplementation(org.apache.ibatis.logging.jdk14.Jdk14LoggingImpl.class);
  }

  public static synchronized void useStdOutLogging() {
    setImplementation(org.apache.ibatis.logging.stdout.StdOutImpl.class);
  }

  public static synchronized void useNoLogging() {
    setImplementation(org.apache.ibatis.logging.nologging.NoLoggingImpl.class);
  }

  private static void tryImplementation(Runnable runnable) {
    // 1. 若 logConstructor 为空，则调用 Runnable.run()方法 ，不是 start（）方法
    if (logConstructor == null) {
      try {
        // 2. 注意这里调用的是 run 方法，也就是当做普通方法执行
        runnable.run();
      } catch (Throwable t) {
        // ignore
      }
    }
  }

  private static void setImplementation(Class<? extends Log> implClass) {
    try {
      // 1. 获取指定适配器的构造方法
      Constructor<? extends Log> candidate = implClass.getConstructor(String.class);
      // 2. 实例化适配器
      Log log = candidate.newInstance(LogFactory.class.getName());
      if (log.isDebugEnabled()) {
        log.debug("Logging initialized using '" + implClass + "' adapter.");
      }
      logConstructor = candidate;
    } catch (Throwable t) {
      throw new LogException("Error setting Log implementation.  Cause: " + t, t);
    }
  }

}
